<template>
  <ul class="gift-list">
    <transition-group name="slide">
      <li v-for="item in poll" :key="item.uid" class="gift-wrap">
        <animate-item :value="item" @complete="handleComplete(item)" />
      </li>
    </transition-group>
  </ul>
</template>

<script>
import _remove from 'lodash/remove'
import _find from 'lodash/find'
import animateItem from './item.vue'
const KEY = 'uid'
export default {
  components: {
    animateItem
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      limit: 3
    }
  },
  computed: {
    pollLength () {
      return this.poll.length
    },
    sourceLength () {
      return this.list.length
    },
    poll () {
      return this.list.slice(0, 3)
    }
  },
  watch: {
    sourceLength: {
      handler (len, oldLen) {
        if (len < oldLen) { // 只计算新增才合并
          return
        }
        const mergedList = this.mergeSourceAmount(this.list)
        this.$emit('update:list', mergedList)
      }
    }
  },
  methods: {
    handleComplete (item) {
      _remove(this.list, { [KEY]: item[KEY] })
      this.$emit('update:list', [...this.list])
    },
    mergeSourceAmount (list) {
      return list.reduce((acc, item) => {
        const find = _find(acc, { [KEY]: item[KEY] })
        if (find) {
          find.amount += item.amount
        } else {
          acc.push(item)
        }
        return acc
      }, [])
    }
  }
}
</script>

<style lang="scss">
.gift-list {
  position: fixed;
  top: 0;
  z-index: 999;
}
.gift-wrap {
  position: relative;
  padding: 20px 0;
}

.slide-enter-active, .slide-leave-active {
  transition: .5s;
}
.slide-enter, .slide-leave-to {
  opacity: 0;
}
</style>
